#include <stdio.h>
#include "ffmpeg_logger.h"
#include "include/libavcodec/avcodec.h"
#include "include/libavformat/avformat.h"
#include "include/libavutil/mathematics.h"
#include "include/libavutil/avutil.h"

int ffmpeg_transcoding_only(char *input_filepath, char *output_filepath) {
    AVPacket pkt;
    AVFormatContext *input_fmtctx = NULL;
    AVFormatContext *output_fmtctx = NULL;
    AVCodecContext *enc_ctx = NULL;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *encoder = NULL;
    int ret = 0;
    int i = 0;

    av_register_all();

    if (avformat_open_input(&input_fmtctx, input_filepath, NULL, NULL) < 0) {
        LOGE("Cannot open the input file %s\n", input_filepath);
        return -ENOENT;
    }

    if (avformat_find_stream_info(input_fmtctx, 0) < 0) {
        LOGE("Failed to retrieve input stream information\n");
        return -EINVAL;
    }

    av_dump_format(input_fmtctx, NULL, input_filepath, 0);

    if (avformat_alloc_output_context2(&output_fmtctx, NULL, NULL, output_filepath) < 0) {
        LOGE("Cannot open the output file %s\n", output_filepath);
        return -ENOENT;
    }

    for (i = 0; i < input_fmtctx->nb_streams; i++) {
        AVStream *out_stream = NULL;
        AVStream *in_stream = NULL;
        in_stream = input_fmtctx->streams[i];
        out_stream = avformat_new_stream(output_fmtctx, NULL);
        if (out_stream < 0) {
            LOGE("Alloc new Stream error\n");
            return -EINVAL;
        }

        dec_ctx = in_stream->codec;

        /* Reencode video & audio and remux subtitles etc. */
        if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
            || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            /* Open decoder */
            AVCodec *decoder = avcodec_find_decoder(dec_ctx->codec_id);
            ret = avcodec_open2(dec_ctx, decoder, NULL);
            if (ret < 0) {
                LOGE("Failed to open decoder for stream #%u\n", i);
                return ret;
            }

            LOGI("dec_ctx->codec_id: %d\n",dec_ctx->codec_id);
            AVCodec *encoder = avcodec_find_encoder(dec_ctx->codec_id);
            enc_ctx = avcodec_alloc_context3(encoder);//h264编码采用avcodec_alloc_context3方式获取enc_ctx
            ret = avcodec_open2(enc_ctx, encoder, NULL);
            if (ret < 0) {
                LOGE("Failed to open encoder for stream #%u\n", i);
                return ret;
            }
        }

        LOGI("avcodec_copy_context start...\n");
        avcodec_copy_context(output_fmtctx->streams[i]->codec, input_fmtctx->streams[i]->codec);
        out_stream->codec->codec_tag = 0;
        if (output_fmtctx->oformat->flags & AVFMT_GLOBALHEADER) {
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }

    }
    av_dump_format(output_fmtctx, NULL, output_filepath, 1);
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    if (avio_open(&output_fmtctx->pb, output_filepath, AVIO_FLAG_WRITE) < 0) {
        LOGE("cannot open the output file '%s'\n", output_filepath);
        return -ENOENT;
    }

    if ((ret = avformat_write_header(output_fmtctx, NULL)) < 0) {
        LOGE("Cannot write the header for the output file '%s' ret = %d\n", output_filepath, ret);
        return -ENOENT;
    }


    while (1) {
        AVStream *in_stream = NULL;
        AVStream *out_stream = NULL;

        ret = av_read_frame(input_fmtctx, &pkt);
        if (ret < 0) {
            LOGE("read frame error %d\n", ret);
            break;
        }

        in_stream = input_fmtctx->streams[pkt.stream_index];
        out_stream = output_fmtctx->streams[pkt.stream_index];
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base,
                                   AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base,
                                   AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;
        ret = av_write_frame(output_fmtctx, &pkt);

        if (ret < 0) {
            LOGE("Muxing Error\n");
            break;
        }
        av_free_packet(&pkt);
    }

    av_write_trailer(output_fmtctx);
    avformat_close_input(&input_fmtctx);
    avio_close(output_fmtctx->pb);
    avformat_free_context(output_fmtctx);

    return 0;

}